package kr.hkit.powerjava.chapter26.service;


import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

import kr.hkit.powerjava.chapter26.dao.DepartmentDAO;
import kr.hkit.powerjava.chapter26.dto.Department;
//DB에 값을 하나씩 넣어주기 위함
public class DepartmentService extends AbsService<Department> {
	//두메서드의 접근이므로 가장 위에 선언
	private ArrayList<Department> list;
	
	public DepartmentService(Scanner sc, Connection connection) {
		super(sc, connection);
		dao= new DepartmentDAO(connection);
	}

	@Override
	public Department inputItemInfo(boolean gubun) {
		System.out.println("학과번호 학과명");
		Department dept = new Department(sc.nextInt(), sc.next().trim());

		if (gubun) {
			System.out.print("위치");
			int floor = sc.nextInt();
			dept.setFloor(floor);
		}
		return dept;
	}

	@Override
	public void prnSubMenu() {
		System.out.print("1. 이름순 정렬 2. 위치별 정렬 3. 번호순 정렬");
		//리스트에 넣자(미리 다 받아서 정렬을 시켜서 보여준다!)
		try {
			//dao클래스 파일을 가리키고 있으므로
			list = dao.listItems();
		} catch (SQLException e) {
			e.printStackTrace();
		}//번호를 선택(고르기)
		int res = sc.nextInt();
		//번호순 정렬(무슨번호를 눌렀냐?)
		switch(res){
			case 1://string 해쉬코드
				prnItemList(new Comparator<Department>() {
					@Override
					public int compare(Department o1, Department o2) {
						return o1.getDeptname().hashCode()-o2.getDeptname().hashCode();
					}
				});
				break;
			case 2:
				prnItemList(new Comparator<Department>() {
					@Override
					public int compare(Department o1, Department o2) {
						return o1.getFloor()-o2.getFloor();
					}
				});
				break;
				//6번이외 눌렀을때
			default:
				prnItemList(null);
		}
	}

	private void prnItemList(Comparator<Department> comparator) {
		if (comparator == null){
			Collections.sort(list);
		}else{
			Collections.sort(list, comparator);
		}
		prnlist(list);
	}

	private void prnlist(ArrayList<Department> list) {
		for(Department d:list){
			System.out.println(d);
		}
	}

}

